#include "devicemanager.h"
#include "ui_devicemanager.h"
#include "ui_deviceinfo.h"
#include <QSqlQuery>
#include <QFileDialog>
#include <QFile>
#include <QTextStream>
#include <QDebug>
#include <QJsonDocument>
#include <QVBoxLayout>
#include <QMenu>
#include <QRect>

DeviceManager::DeviceManager(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::DeviceManager)
    , common(this)
    ,showBtnsflag(true)
{
    ui->setupUi(this);
    Logger().init();
    headerNames = {"选择", "设备名称", "设备类型", "位置", "制造商", "型号", "安装日期","设备ID"};
    tableNames={"","name","type","location","manufacturer","model","installation_date","device_id"};
    m_pDeviceInfo=new DeviceInfo;
    model = new QStandardItemModel(this);
    proxyModel = new QSortFilterProxyModel(this);
    proxyModel->setSourceModel(model);
    ui->deviceManagerTable->setModel(proxyModel);
    // 将模型设置到视图
    header = new TableViewHeader(Qt::Horizontal, ui->deviceManagerTable);
    //header->setGroupColumn(0);
    header->setModel(model);

    ui->deviceManagerTable->setHorizontalHeader(header);
    ui->deviceManagerTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); //自适应
    ui->deviceManagerTable->setSortingEnabled(true);   //视图开启排序
    ui->deviceManagerTable->horizontalHeader()->setSortIndicatorShown(true); //视图排序指示器
    connects();
    common.loadQssfromfile(":/qss/deviceManegerQSS.qss");
    db=  SQLiteDatabase::getInstance();

    onShowView();
}
/*排序查询*/
void DeviceManager::onSortButtonClicked(int logicalIndex) {
    qDebug() << "Sort button clicked at column" << logicalIndex;
    Qt::SortOrder currentOrder = ui->deviceManagerTable->horizontalHeader()->sortIndicatorOrder();
    ui->deviceManagerTable->sortByColumn(logicalIndex, currentOrder == Qt::AscendingOrder ? Qt::DescendingOrder : Qt::AscendingOrder);
}
/*分组查询*/
void DeviceManager::onShowView(const QString querySql){
    qDebug()<<"DEBUG : onShowView "<<querySql;
    model->clear();
    model->setColumnCount(tableNames.size());
    model->setHorizontalHeaderLabels(headerNames);
    QSqlQuery query(db->getConnection());
    query.prepare(querySql);
    if (!query.exec()) {
        qCritical() << "Failed to load alarm rules:" << query.lastError().text();
        return;
    }
    qDebug()<<"select from device";
    while (query.next()) {
        QList<QStandardItem *> rowItems;
        QStandardItem *checkItem = new QStandardItem();
        checkItem->setCheckable(true);
        rowItems.append(checkItem);
        for(int i =1;i<tableNames.size();i++){rowItems.append(new QStandardItem(query.value(tableNames[i]).toString()));}
        model->appendRow(rowItems);
    }
}
/*普通查询*/
void DeviceManager::readDeviceManager(){
    model->clear();
    model->setColumnCount(tableNames.size());
    //for(int i =0;i<headerNames.size();i++){model->setHeaderData(0,Qt::Horizontal, tr(headerNames[i].toUtf8()));}
    model->setHorizontalHeaderLabels(headerNames);
    QSqlQuery query(db->getConnection());
    QString querySql="SELECT * FROM devices";
    query.prepare(querySql);
    if (!query.exec()) {
        qCritical() << "Failed to load alarm rules:" << query.lastError().text();
        return;
    }

    while (query.next()) {
        QList<QStandardItem *> rowItems;
        QStandardItem *checkItem = new QStandardItem();
        checkItem->setCheckable(true);
        rowItems.append(checkItem);
        for(int i =1;i<tableNames.size();i++){rowItems.append(new QStandardItem(query.value(tableNames[i]).toString()));}
        model->appendRow(rowItems);
    }
    //添加操作一列
    //int columnCount = model->columnCount();
    //qDebug()<<columnCount;
    //model->insertColumns(columnCount, 1);
    //columnCount = model->columnCount();

    //ui->deviceManagerTable->setColumnHidden(0, true);
    //设置操作列上的行修改和行删除按钮，未实现
    //ButtonDelegate *delegate = new ButtonDelegate(this);
    //ui->deviceManagerTable->setItemDelegateForColumn(columnCount, delegate);
    //connect(delegate, &ButtonDelegate::editClicked, this, &DeviceManager::onEditClicked);
    //connect(delegate, &ButtonDelegate::deleteClicked, this, &DeviceManager::onDeleteClicked);
}

void DeviceManager::connects(){
    connect(ui->deviceInfoBtn, &QPushButton::clicked, this, &DeviceManager::onCreateDeviceInfo);
    connect(ui->modifyBtn, &QPushButton::clicked, this, &DeviceManager::onModifyDeviceInfo);
    connect(ui->deleteBtn, &QPushButton::clicked, this, &DeviceManager::onDeleteDeviceInfo);
    connect(this, &DeviceManager::sinDeviceEdit, m_pDeviceInfo, &DeviceInfo::onSetDeviceId);
    connect(m_pDeviceInfo, &DeviceInfo::sinMainReFlash, this, &DeviceManager::onShowView);
    connect(ui->deviceListBtn, &QPushButton::clicked, this, &DeviceManager::onShowDeviceList);
    connect(ui->deviceManagerBrn, &QPushButton::clicked, this, &DeviceManager::onSetBtns);
    connect(ui->importBtn, &QPushButton::clicked, this, &DeviceManager::onImportDevices); // 连接导入按钮
    connect(header, &TableViewHeader::groupButtonClicked, this, &DeviceManager::onGroupButtonClicked);
    connect(header, &TableViewHeader::sortButtonClicked, this, &DeviceManager::onSortButtonClicked);
    connect(ui->queryBtn, &QPushButton::clicked, this, &DeviceManager::readDeviceManager);
}

void DeviceManager::onGroupButtonClicked(int logicalIndex) {
    qDebug()<<"DEBUG : onSectionClicked "<<logicalIndex;
    QString selectname =tableNames[logicalIndex];
    qDebug()<<"DEBUG : onSectionClicked "<<selectname;
    QString querySql=QString("SELECT %1 FROM devices group by %1;").arg(selectname);
    QSqlQuery query;
    QMenu menu;
    query.prepare(querySql);
    if (!query.exec()) {
        qCritical() << "Failed to load alarm rules:" << query.lastError().text();
        return;
    }
    while (query.next()) {
        const QString downName=query.value(selectname).toString();
        QAction *actionTypeA = menu.addAction(downName );
        const QString sql=QString("select * FROM devices where %1 = '%2';").arg(selectname).arg(downName);
        connect(actionTypeA, &QAction::triggered, this, [=]() { onShowView(sql);} );
    }
    // 获取表头的矩形位置
    int headerPos = ui->deviceManagerTable->horizontalHeader()->sectionViewportPosition(logicalIndex);
    QPoint globalPos = ui->deviceManagerTable->horizontalHeader()->viewport()->mapToGlobal(QPoint(headerPos, logicalIndex));
    QRect rect(globalPos, QSize(ui->deviceManagerTable->horizontalHeader()->sectionSize(logicalIndex), ui->deviceManagerTable->horizontalHeader()->height()));
    menu.exec(rect.bottomLeft());
}


QJsonObject DeviceManager::getViewActualDevicesIdbyLine(){
    //点击行获取deviceID
    QModelIndex m_qModelIndex= ui->deviceManagerTable->currentIndex();
    int index=m_qModelIndex.row();
    qDebug()<<"index:"<<index;
    QString cmd=QString("1=1 limit %1").arg(index+1);
    qDebug()<<"cmd:"<<cmd;
    QJsonArray devicesArray = db->read("devices",cmd);
    QJsonObject obj;
    if (!devicesArray.isEmpty()) {
        obj = devicesArray.at(index).toObject(); // Use at() and adjust index

    } else {
        qDebug() << "devicesArray is empty";
    }
    return obj;
}

QJsonArray DeviceManager::getViewActualDevicesIdbySelectBox(){
    QJsonArray array;
    int rowCount = model->rowCount();// 获取模型中的行数
    QList<int> selectedRows;// 用于存储选中的行的索引
    // 遍历所有行，检查复选框是否勾选
    int maxRow=-1;
    for (int row = 0; row < rowCount; ++row) {
        maxRow=row;
        QStandardItem *item = model->item(row, 0); // 假设复选框在第0列
        if (item && item->checkState() == Qt::Checked) {
            selectedRows.append(row);
        }
    }
    QString cmd=QString("1=1 limit %1").arg(maxRow+1);
    qDebug()<<"cmd:"<<cmd;
    QJsonArray devicesArray = db->read("devices",cmd);
    QJsonObject obj;
    if (!devicesArray.isEmpty()) {
        for(int index : selectedRows){
            obj = devicesArray.at(index).toObject(); // Use at() and adjust index
            array.append(obj);
        }
    } else {
        qDebug() << "devicesArray is empty";
    }
    return array;
}

void DeviceManager::onCreateDeviceInfo(){
    qDebug()<<"打开设备信息界面";
    m_pDeviceInfo->getUI()->deviceNameEdit->clear();
    m_pDeviceInfo->getUI()->deviceTypeEdit->clear();
    m_pDeviceInfo->getUI()->deviceLocatorEdit->clear();
    m_pDeviceInfo->getUI()->deviceManufacturerEdit->clear();
    m_pDeviceInfo->getUI()->deviceModelEdit->clear();
    m_pDeviceInfo->getUI()->deviceDateEdit->setDisplayFormat("yyyy-MM-dd"); // 设置日期显示格式，根据需要调整
    m_pDeviceInfo->getUI()->deviceDateEdit->setDate(QDate::currentDate()); // 设置日期为当前日期
    m_pDeviceInfo->show();
    emit sinDeviceEdit(0);
}

void DeviceManager::onModifyDeviceInfo(){
    QJsonObject obj=getViewActualDevicesIdbyLine();
    qDebug() << "Selected JSON Object:" << obj;
    QString deviceId = obj.value("device_id").toString();
    QString deviceName = obj.value("name").toString();
    QString deviceModel = obj.value("model").toString();
    QString deviceType = obj.value("type").toString();
    QString deviceLocator= obj.value("location").toString();
    QString deviceManufacturer= obj.value("manufacturer").toString();
    QString deviceDate= obj.value("installation_date").toString();
    QDate date = QDate::fromString(deviceDate, "yyyy-MM-dd");
    if(deviceId.toInt()>0){
        onCreateDeviceInfo();
        m_pDeviceInfo->getUI()->deviceNameEdit->setText(deviceName);
        m_pDeviceInfo->getUI()->deviceTypeEdit->setText(deviceType);
        m_pDeviceInfo->getUI()->deviceLocatorEdit->setText(deviceLocator);
        m_pDeviceInfo->getUI()->deviceManufacturerEdit->setText(deviceManufacturer);
        m_pDeviceInfo->getUI()->deviceModelEdit->setText(deviceModel);
        m_pDeviceInfo->getUI()->deviceDateEdit->setDate(date);
        emit sinDeviceEdit(deviceId.toInt());
    }else{
        common.createMessageBox("提示","请选择一行");
    }
}

void DeviceManager::onDeleteDeviceInfo(){
    QString name,type,location,manufacturer,model,installation_date,device_id;
    QJsonArray jsonArray=getViewActualDevicesIdbySelectBox();
    if(jsonArray.size()>0){
        bool msgflag=common.createMessageBox("选择","确认删除吗？");
        if(!msgflag){
            return;
        }
        for (const QJsonValue &value : jsonArray) {
            if (value.isObject()) {
                const QJsonObject &obj = value.toObject();
                name=obj["name"].toString();
                type=obj["type"].toString();
                location=obj["location"].toString();
                manufacturer=obj["manufacturer"].toString();
                model=obj["model"].toString();
                installation_date=obj["installation_date"].toString();
                device_id=obj["device_id"].toString();
                qDebug() << "Selected JSON Object:" << obj;
                QString deviceIndexCmd=QString("device_id=%1").arg(device_id);
                qDebug()<<"deviceIndexCmd:"<<deviceIndexCmd;
                db->deleteRecord("devices", deviceIndexCmd);
                logText=QString("删除设备成功: devices:%1,name:%2,type:%3,location:%4,manufacturer:%5,model:%6,installation_date:%7").
                          arg(device_id).arg(name).arg(type).arg(location).arg(manufacturer).arg(model).arg(installation_date);
                Logger().logDebug(logText);
            }
        }
        onShowView();
        common.createMessageBox("提示","删除成功!");
    }else{
        common.createMessageBox("错误","请勾选一行");
    }
}

void DeviceManager::onEditClicked(const QModelIndex &index){
    qDebug() << "Edit clicked on row" << index.row();
}

void DeviceManager::onDeleteClicked(const QModelIndex &index){
    qDebug() << "Delete clicked on row" << index.row();
}

void DeviceManager::onShowDeviceList(){
    ui->rightWidget->show();
    qDebug() << "show widget_2";
}

void DeviceManager::onSetBtns(){
    if(showBtnsflag){
        ui->deviceListBtn->show();
    }else{
        ui->deviceListBtn->hide();
    }
    showBtnsflag=!showBtnsflag;
}

void DeviceManager::ReceiveLogininformation(QString &userName, QString &role)
{

    qDebug()<<userName<<role;
    if(role=="user"){
        ui->deviceInfoBtn->setEnabled(false);
        ui->deleteBtn->setEnabled(false);
        ui->modifyBtn->setEnabled(false);
        ui->importBtn->setEnabled(false);
        ui->importBtn->setVisible(false);
        ui->deviceInfoBtn->setVisible(false);
        ui->deleteBtn->setVisible(false);
        ui->modifyBtn->setVisible(false);
    }
}

void DeviceManager::onImportDevices()
{
    QString fileName = QFileDialog::getOpenFileName(this, tr("Open Device File"), "", tr("JSON Files (*.json);;CSV Files (*.csv);;All Files (*)"));
    if (fileName.isEmpty()) {
        return;
    }

    QFile file(fileName);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qCritical() << "Cannot open file for reading:" << file.errorString();
        return;
    }

    if (fileName.endsWith(".json")) {
        QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
        if (doc.isArray()) {
            QJsonArray array = doc.array();
            for (const QJsonValue &value : array) {
                if (value.isObject()) {
                    QJsonObject obj = value.toObject();
                    QString name = obj["name"].toString();
                    QString type = obj["type"].toString();
                    QString location = obj["location"].toString();
                    QString manufacturer = obj["manufacturer"].toString();
                    QString model = obj["model"].toString();
                    QString installation_date = obj["installation_date"].toString();

                    QSqlQuery query(db->getConnection());
                    query.prepare("INSERT INTO devices (name, type, location, manufacturer, model, installation_date) VALUES (?, ?, ?, ?, ?, ?)");
                    query.addBindValue(name);
                    query.addBindValue(type);
                    query.addBindValue(location);
                    query.addBindValue(manufacturer);
                    query.addBindValue(model);
                    query.addBindValue(installation_date);

                    if (!query.exec()) {
                        qCritical() << "Failed to insert device:" << query.lastError().text();
                    }
                }
            }
        }
    } else if (fileName.endsWith(".csv")) {
        QTextStream in(&file);
        while (!in.atEnd()) {
            QString line = in.readLine();
            QStringList fields = line.split(",");
            if (fields.size() >= 6) {
                QString name = fields[0];
                QString type = fields[1];
                QString location = fields[2];
                QString manufacturer = fields[3];
                QString model = fields[4];
                QString installation_date = fields[5];

                QSqlQuery query(db->getConnection());
                query.prepare("INSERT INTO devices (name, type, location, manufacturer, model, installation_date) VALUES (?, ?, ?, ?, ?, ?)");
                query.addBindValue(name);
                query.addBindValue(type);
                query.addBindValue(location);
                query.addBindValue(manufacturer);
                query.addBindValue(model);
                query.addBindValue(installation_date);

                if (!query.exec()) {
                    qCritical() << "Failed to insert device:" << query.lastError().text();
                }
            }
        }
    }

    file.close();
    onShowView(); // 更新设备列表
}


DeviceManager::~DeviceManager()
{
    delete ui;
    delete model;
    delete header;
    delete m_pDeviceInfo;
    delete proxyModel;
}
